/**
 * 需要知道animationClip
 * 需要播放动画能力animation
 */
import { AnimationClip, animation, Sprite, SpriteFrame } from 'cc'
import ResourceManager from '../Runtime/ResourceManager'
import { StateMachine } from './StateMachine'
import { sortSpriteFrame } from '../Utils'

export const ANIMATION_SPEED = 1 / 8 // 1秒8帧
export default class State {
  animationClip: AnimationClip
  constructor(
    private fsm: StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
    private speed: number = ANIMATION_SPEED,
    private events: any[] = [],
  ) {
    this.init()
  }
  // 渲染人物
  async init() {
    // 加载资源文件夹
    const promise = ResourceManager.Instance.loadDir(this.path)
    this.fsm.waitingList.push(promise)
    const spriteFrames = await promise
    this.animationClip = new AnimationClip()
    // 设置名称，目的为了判断取消
    this.animationClip.name = this.path
    // 创建一个对象轨道
    const track = new animation.ObjectTrack()
    // 添加轨道路径为Sprite组件
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')

    const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteFrames).map((item, index) => [
      index * this.speed,
      item,
    ])

    // 设置一条通道channel的关键帧
    track.channel.curve.assignSorted(
      frames,
      /*      [
      // 为 x 通道的曲线添加关键帧
      [0.4, { value: 0.4 }], //[时间,属性]
      [0.6, { value: 0.6 }],
      [0.8, { value: 0.8 }],
    ]*/
    )
    // 最后将轨道添加到动画剪辑以应用
    this.animationClip.addTrack(track)
    // 整个动画剪辑的周期 帧数*帧率
    this.animationClip.duration = frames.length * this.speed
    // 循环播放
    this.animationClip.wrapMode = this.wrapMode

    for (const event of this.events) {
      this.animationClip.events.push(
        event,
        // {
        // frame: 0.5, // 第 0.5 秒时触发事件
        // func: 'onTriggered', // 事件触发时调用的函数名称
        // params: ['0'], // 向 `func` 传递的参数
        // }
      )
    }
    this.animationClip.updateEventDatas()
  }
  run() {
    if (this.fsm.animationComponent?.defaultClip?.name === this.animationClip.name) {
      return
    }
    // 设置动画，defaultClip,并且播放
    this.fsm.animationComponent.defaultClip = this.animationClip
    this.fsm.animationComponent.play()
  }
}
